package br.com.projeto.model.persistencia.daos;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import br.com.projeto.model.entities.Fase;
import br.com.projeto.model.entities.Projeto;
import br.com.projeto.model.persistencia.DAO;
import br.com.projeto.model.persistencia.EntityManagerHelper;

public class FaseDAO extends DAO<Fase> {
	public FaseDAO() {
		super(Fase.class);
	}

	@SuppressWarnings("unchecked")
	public List<Fase> listar(Projeto projeto, Date inicio, Date termino) {
		EntityManager context = EntityManagerHelper.getEntityManager();
		try {

			return context.createQuery("FROM Fase f WHERE f.projeto.id = :id AND f.inicio <= :termino AND f.termino >= :inicio")
					.setParameter("inicio",inicio)
					.setParameter("termino", termino)
					.setParameter("id", projeto.getId())
					.getResultList();

		} catch (Exception e) {
			return null;
		} finally {
			context.close();
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Fase> listar(Projeto projeto) {

		EntityManager context = EntityManagerHelper.getEntityManager();
		try {

			return context.createQuery("from Fase f where f.projeto.id = :id")
					.setParameter("id", projeto.getId()).getResultList();

		} catch (Exception e) {
			return null;
		} finally {
			context.close();
		}

	}

	public void criar(Fase fase) {
		EntityManager context = EntityManagerHelper.getEntityManager();
		EntityTransaction transaction = context.getTransaction();
		try {
			transaction.begin();
			context.persist(fase);
			HistoricoDAO.registrar(context).novaFase(fase);
			
			transaction.commit();
		} finally {
			if (transaction.isActive())
				transaction.rollback();
			context.close();
		}

	}

}
